// js/main.js

document.addEventListener('DOMContentLoaded', () => {
    console.log("DOM fully loaded and parsed");

    setupCanvases(); // 初始化 Canvas 尺寸和缩放

    // --- 事件监听器 ---

    // 开始/重新开始按钮
    startButton.addEventListener('click', () => {
        console.log("Start button clicked");
        startGame();
    });

    // 查看排行榜按钮
    leaderboardButton.addEventListener('click', async () => {
        console.log("Leaderboard button clicked");
        setStatusMessage(leaderboardStatusElement, '正在加载...', false);
        showLeaderboardModal([]); // 先显示空弹窗和加载信息
        try {
            const scores = await getLeaderboard();
            showLeaderboardModal(scores); // 使用获取的数据更新弹窗
        } catch (error) {
            setStatusMessage(leaderboardStatusElement, `加载失败: ${error.message}`, true);
            // 保留弹窗打开状态，显示错误信息
        }
    });

    // 关闭排行榜按钮
    closeLeaderboardButton.addEventListener('click', () => {
        hideLeaderboardModal();
    });

    // 刷新排行榜按钮
    refreshLeaderboardButton.addEventListener('click', async () => {
         console.log("Refresh leaderboard clicked");
         setStatusMessage(leaderboardStatusElement, '正在刷新...', false);
         leaderboardContentElement.innerHTML = '<p>加载中...</p>'; // 显示加载状态
         try {
            const scores = await getLeaderboard();
            showLeaderboardModal(scores); // 更新内容
         } catch (error) {
            setStatusMessage(leaderboardStatusElement, `刷新失败: ${error.message}`, true);
         }
    });


    // 提交分数按钮
    submitScoreButton.addEventListener('click', async () => {
        const playerName = playerNameInput.value.trim();
        if (!playerName) {
            setStatusMessage(submitStatusElement, '请输入昵称!', true);
            return;
        }
        if (playerName.length > 50) {
             setStatusMessage(submitStatusElement, '昵称不能超过50个字符!', true);
            return;
        }

        const currentFinalScore = parseInt(finalScoreElement.textContent || '0');
        console.log(`Submitting score: ${playerName}, ${currentFinalScore}`);
        setStatusMessage(submitStatusElement, '正在提交...', false);
        submitScoreButton.disabled = true; // 防止重复提交

        try {
            await submitScore(playerName, currentFinalScore);
            setStatusMessage(submitStatusElement, '提交成功!', false);
            // 提交成功后可以考虑自动刷新并显示排行榜
            // 或者只是提示成功，让用户手动查看
            // 可选：禁用提交按钮，直到重新开始
        } catch (error) {
            setStatusMessage(submitStatusElement, `提交失败: ${error.message}`, true);
            submitScoreButton.disabled = false; // 提交失败，允许重试
        }
    });

    // 重新开始按钮 (在游戏结束弹窗里)
    restartButton.addEventListener('click', () => {
        console.log("Restart button clicked from modal");
        hideGameOverModal();
        startGame(); // 开始新游戏
    });

    // 键盘事件监听
    document.addEventListener('keydown', handleInput);

    // --- 初始状态 ---
    // 可以绘制一个初始的空棋盘或欢迎信息
    clearCanvas(ctx, canvas);
    clearCanvas(nextCtx, nextCanvas);
    console.log("Game initialized, ready to start.");
});